package cn.lirenyi.user.controller;

import cn.lirenyi.basic.exception.BusinessException;
import cn.lirenyi.basic.util.AjaxResult;
import cn.lirenyi.basic.util.PageList;
import cn.lirenyi.user.Dto.UserDto;
import cn.lirenyi.user.domain.User;
import cn.lirenyi.user.query.UserQuery;
import cn.lirenyi.user.service.IUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口",description = "用户接口详细功能")
public class UserController {

    @Autowired
    private IUserService service;

    @GetMapping("/{id}")    // 相当于@RequestMapping(value="/id",method = RequestMethod.GET)
    // 根据id查
    public User queryById(@PathVariable("id") Long id){
        return service.queryById(id);
    }

    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user){
        // 先判断有无id，进而判断是添加还是修改方法
        try {
            // 没有id就是添加
            if (user.getId() == null){
                service.add(user);
            } else {
                // 有id就是修改
                service.update(user);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作失败");
        }

    }

    @DeleteMapping("/{id}")     // 删除
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            service.del(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("艸作失败");
        }
    }

    @PostMapping    // 分页查询
    public PageList<User> queryPage(@RequestBody UserQuery userQuery){
        PageList<User> page = service.queryPage(userQuery);
        System.out.println(page);
        return page;
    }

    @GetMapping    // 查全部
    public List<User> queryAll(){
        return service.queryAll();
    }


    @PatchMapping     // 批量删除
    public AjaxResult patchDel(@RequestBody Long[] id){
        try {
            service.patchDel(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("艸作失败");
        }
    }

    @PostMapping("/register/phone")
    public AjaxResult register(@RequestBody UserDto userDto){
        try {
            service.register(userDto);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统发生错误，我们正在殴打前端");
        }
    }



}
